import { routerRedux } from 'dva/router';
import $$ from 'utils';
import {baseEffects, baseReducers} from "../../../../models/baseModel";
import * as request from "../../../../services/CommonHttpService";

export default {
  namespace: 'login',

  state: {
    loggedIn: false,
    loading: false,
    user: {},
  },

  subscriptions: {
    setup({history, dispatch}) {
      return history.listen(({pathname}) => {
        if (pathname.indexOf('/sign/login') !== -1) {
          $$.removeStore('user');
        }
      });
    }
  },

  reducers: {

    ...baseReducers,

    loginSuccess(state, {payload}) {
      return {
        ...state,
        loggedIn: true,
        user: payload
      };
    },
    loginError(state, {payload}) {
      return {
        ...state,
        loggedIn: false,
      };
    },
  },

  effects: {

    ...baseEffects,

    * login({payload}, {call, put}) {
      const {filters, errorMsg, notice, server} = payload;
      const {userName, password} = filters;

      yield put({
        type: 'initState',
        payload: {
          loading: true,
        }
      });

      const params = {
        grant_type: "password", scope: "all", client_id: "mlnx", client_secret: "medgen2011",
        username: userName, password: password
      };

      try {
        let result = yield call(request.login, {}, params, server);
        $$.setStore("user", result);
        yield put(routerRedux.replace('/'));
        yield put({
          type: 'initState',
          payload: {
            loading: false,
          }
        });
      } catch (error) {
        console.error("login", error);
        !!notice && notice("error", !!errorMsg ? errorMsg : error);
        yield put({
          type: 'initState',
          payload: {
            loading: false,
          }
        });
      }
    },
    * logout(_, {put}) {

    }
  },
};
